#!/usr/bin/perl

## This file is part of the Simplemail project.
#  Copyright (c) 2008 the Simplemail Team (see authors).
#
#  For the full copyright and license information, please view the COPYING
#  file that was distributed with this source code. You can also view the
#  COPYING file online at http://unixforum.org.ua/misc/COPYING.txt
#
#  @copyright  (c) the authors
#  @author     Dmitriy Shilenko <rtyug@ukr.net>
#  @license    GPLv2 http://unixforum.org.ua/misc/COPYING.txt
#  @package    Panel Mailbox
#  @version    $Id: $

use strict;
use DBI;
use Fcntl ':flock';
use File::Pid;

my $pidfile = File::Pid->new( { file => '/var/run/simplemail.pid', } );

#  my $pid = $pidfile->pid;
#  print $pid;
#  use POSIX 'getpid';
#  my $pid_script = &getpid;
#  print $pid_script;

# my $num = $pidfile->running;
#  if ($pid_script == $num) {
#   die "Already running: $num\n";
#  }

my $pid = $pidfile->running;
die "Service already running: $pid\n" if $pid;

$pidfile->write;

our $se;

require "/usr/local/www/simplemail/lib/config.pl";

unless ( -e ( $se->{'maildir'} ) ) {
    print "error dir mail from config.pl";
    exit;
}

my $dbh = DBI->connect( $se->{dsn}, $se->{db_user}, $se->{db_pass}, { RaiseError => 1 } )
  || die $DBI::errstr;

############### delete maillog old
my $sth = $dbh->prepare(
    'SELECT min(id) AS min_id,
                                             max(id) AS max_id 
                             FROM maillog
                             '
);
$sth->execute();
my $id = $sth->fetchrow_hashref();
$sth->finish();

my $total_id = $id->{'max_id'} - $id->{'min_id'};
my $delete_id;
if (   $total_id > $se->{'time_which_active_logmta'}
    && $se->{'time_which_active_logmta'} > 0 )
{
    $delete_id = $total_id - $se->{'time_which_active_logmta'};
}

if ( $delete_id > 0 ) {

    my $delete_id2 = $id->{'min_id'} + $delete_id;

    $dbh->do( qq{DELETE FROM maillog WHERE id < ?}, undef, $delete_id2 );

}

############### delete log simplemail old

if ( $se->{'time_which_active_logsm'} > 0 ) {

    my $delete_time = time - $se->{'time_which_active_logsm'};

    $dbh->do( qq{DELETE FROM log_smail WHERE created < ?}, undef,
        $delete_time );
}

############### delete mailbox

my $sth = $dbh->prepare(
    'SELECT domain,
                                    mailbox
                             FROM mailbox_delete
                             '
);
$sth->execute();

my @loop_data;
while ( my $ref = $sth->fetchrow_hashref() ) { push( @loop_data, $ref ); }
$sth->finish();

for my $row (@loop_data) {
    my $dir =
      $se->{'maildir'} . '' . $row->{'domain'} . '/' . $row->{'mailbox'};
    system("rm -Rf $dir");

    $dbh->do( qq{DELETE FROM mailbox_delete WHERE mailbox = ?},
        undef, $row->{'mailbox'} );
}

############### delete domain

my $sth = $dbh->prepare(
    'SELECT domain
                             FROM domain_delete
                             '
);
$sth->execute();

my @loop_data;
while ( my $ref = $sth->fetchrow_hashref() ) { push( @loop_data, $ref ); }
$sth->finish();

for my $row (@loop_data) {
    my $dir = $se->{'maildir'} . '' . $row->{'domain'};
    system("rm -Rf $dir");

    $dbh->do( qq{DELETE FROM domain_delete WHERE domain = ?},
        undef, $row->{'domain'} );
}

$dbh->disconnect;

############### END

############### maillog

if ( $se->{'active_logmta'} eq '1' ) {

    open LOG, '<', $se->{maillog} or die "Can't open $se->{maillog}: $!\n";
    flock( LOG, LOCK_EX );
    my $pos = 0;
    $pos = do { chomp; $_ } while <DATA>;
    seek LOG, $pos, 0 if $pos <= -s $se->{maillog};

    my $dbh = DBI->connect(
        "DBI:$se->{db_type}:database=$se->{db_name};host=$se->{db_host}",
        $se->{db_user}, $se->{db_pass}, { RaiseError => 1 } )
      || die $DBI::errstr;

    while ( my $line = <LOG> ) {
        my ( $month, $day, $time, $hostname, $servicename ) = split / /, $line,
          5;

        my $timedata = $month . ' ' . $day . ' ' . $time;
        my $text     = $hostname . ' ' . $servicename;

        $dbh->do( qq{INSERT INTO maillog (data,text) VALUES(?,?)},
            undef, $timedata, $text );
    }

    $dbh->disconnect;

    $pos = tell LOG;
    flock( LOG, LOCK_UN );
    close LOG;

    $pidfile->remove;    #or warn "Couldn't unlink pid file\n";

    exec qw(perl -0777 -i -pe), 's/$/\n' . $pos . '/', $0;
    exit;
}

$pidfile->remove;        #or warn "Couldn't unlink pid file\n";
exit;

__DATA__
137093
137093
140468
141590
142712
